'use strict';
const FStream = require('fs');

/**
 * 版本信息生成插件
 * @param options
 * @constructor
 */
const packageInfo = require('../../package.json');
function VersionPlugin(options) {
  this.options = options || {};
  !this.options.versionDirectory && (this.options.versionDirectory = 'static');
}

// apply方法是必须要有的，因为当我们使用一个插件时（new somePlugins({})），webpack会去寻找插件的apply方法并执行
VersionPlugin.prototype.apply = function (compiler) {
  var self = this;
  compiler.plugin('compile', function (params) {
    var dirPath = (self.options.rootPath + 'public/') + self.options.versionDirectory;
    var versionFile = dirPath + '/version.json';
    var content = '{"version":"' + packageInfo.version + '"}';
    FStream.exists(dirPath, function (exist) {
      console.log(dirPath);
      if (exist) {
        writeVersion(self, versionFile, content);
        return;
      }
      FStream.mkdir(dirPath, function (err) {
        if (err) throw err;
        console.log('\n创建目录[' + dirPath + ']成功');
        writeVersion(self, versionFile, content);
      });
    });
  });
  // 编译器对'所有任务已经完成'这个事件的监听
  compiler.plugin('done', function (stats) {
    console.log('\n应用编译完成！');
  });
};

const writeVersion = (self, versionFile, content) => {
  console.log('\n当前版本号：' + packageInfo.version);
  console.log('开始写入版本信息...');
  // 写入文件
  FStream.writeFile(versionFile, content, function (err) {
    if (err) throw err;
    console.log('版本信息写入成功!');
  });
};

module.exports = VersionPlugin;
